package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;
    @Override
    public void add(Address address) {
        addressDao.add(address);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Address> page = addressDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void delete(Integer id) {
        addressDao.deleteById(id);
    }

    @Override
    public Address findById(Integer id) {
        Address address = addressDao.findById(id);
        return address;
    }

    @Override
    public void edit(Address address) {
        addressDao.edit(address);
    }

    @Override
    public List<Map> findAllAddress() {
        List<Address> list = addressDao.findAllAddress();
       List<Map> result = new ArrayList<>();
        for (Address address : list) {
            Map<String,Object> map = new HashMap<>();
            String detailAddress = address.getAddress();
            String name = detailAddress+address.getName();
            String longitudeAndLatitude = address.getLongitudeAndLatitude();
            String[] split = longitudeAndLatitude.split(",");
            String longitude = split[0];
            String latitude = split[1];

            map.put("name",name);
            map.put("longitude",longitude);
            map.put("latitude",latitude);
            map.put("longitudeAndLatitude",longitudeAndLatitude);
            result.add(map);
        }
        return result;
    }
}
